<template>
	<view class="padding" :class="theme">
		<view class="text-red margin-bottom" v-if="orderData.status == 14">
			<template v-if="orderData.delayAuditReason && orderData.delayAuditReason !== ''">
				您提交的订单异常审核未通过！原因：{{ orderData.delayAuditReason }}! 请您完善信息后再提交！
			</template>
			<template v-else>
				您提交的订单异常审核未通过！暂无原因! 请您完善信息后再提交！
			</template>
		</view>
		<view class="text-red margin-bottom" v-if="orderData.status == 4 && orderData.isStatus == 2 && theme == 'fs'">
			<template v-if="orderData.auditReason && orderData.auditReason !== ''">
				您提交的订单完工审核未通过！原因：{{ orderData.auditReason }}! 请您完善信息后再提交！
			</template>
			<template v-else>
				您提交的订单完工审核未通过！暂无原因! 请您完善信息后再提交！
			</template>
		</view>

		<view v-if="theme=='fs'|| theme == 'farmer'&& orderData.flyerName"
			class="bg-white radius-lg margin-bottom padding">
			<view class="text-lg text-bold padding-bottom-sm solid-bottom">
				<text class="cuIcon-titles " :class="theme == 'fs'?'color-blue':'color-green'"></text>
				<text v-if="theme == 'farmer'" class="text-black">飞手信息</text>
				<text v-else class="text-black">户主信息</text>
			</view>
			<view class="flex align-center justify-between margin-top-sm">
				<view class="flex align-center">
					<view class='cu-avatar round lg ov-h'>
						<image v-if="theme == 'farmer'" :src="`${$hd.baseUrl}/images/flyer.png`" mode="aspectFit">
						</image>
						<image v-else :src="`${$hd.baseUrl}/images/farmer.png`" mode="aspectFit"></image>
					</view>
					<view class="margin-left-sm">
						<view class="text-black text-bold text-lg">
							{{theme == 'farmer'? orderData.flyerName : orderData.regionContact}}
						</view>
						<!-- <view class="text-gray margin-top-xs">
							发单次数：{{orderData.regionPhone}}
						</view> -->
					</view>
				</view>
				<view v-if="orderData.status>=2&&orderData.status !=9&&orderData.status != 17" class="solid-left padding-left" @click="handleCallPhone">
					<uv-icon name="phone-fill" color="#FE3566" size="30"></uv-icon>
					<view class="margin-top-xs text-black">
						电话
					</view>
				</view>

			</view>
		</view>

		<!-- 订单信息 -->
		<OrderDetailCard :orderData="orderData" />

		<!-- 查看过人 -->
		<!-- <view class="padding flex align-center justify-center">
			<text class="text-gray">共有126人查看过该订单！</text>
			<uv-avatar-group :urls="urls" size="35" gap="0.4"></uv-avatar-group>
		</view> -->

		<!-- 监控信息 -->
		<MonitorInfo v-if="orderData.status !== 1 && orderData.status !== 17" :fisrtData="fisrtData" :monitorData="monitorData" />

		<!-- 作业信息 -->
		<WorkInfo v-if="picData.drugImage.length>0" :picData="picData" />

		<!-- 结算信息 -->
		<SettleInfo v-if="orderData.actualMoney" :orderData="orderData" />

		<!-- 评价信息 -->
		<EvaluateInfo v-if="theme == 'farmer' && orderData.commentStar" :commentStar="orderData.commentStar"
			:commentContent="orderData.commentContent" />


		<!-- <uv-modal ref="orderTip" title="抢单提示" cancelColor="#006BFE" :showCancelButton="true" confirmText="确定"
			@confirm="confirmAdd">
			<view class="slot-content">
				<view class="text-center">
					您确定要抢接该订单吗？
				</view>
			</view>
		</uv-modal> -->

		<!-- 认证提示 -->
		<!-- <uv-modal ref="auth" title="抢单提示" cancelColor="#006BFE" content="您还未完成飞手认证，请先前往完成认证再进行抢单！"
			:showCancelButton="true" confirmText="确定" @confirm="confirmAdd">
		</uv-modal> -->

		<view class="h-100"></view>

		<view class="foot-box">
			<view v-if="theme=='fs'&&orderData.orderType == 1&&robFlag&&(orderData.status == 1 || orderData.status == 17)"
				style="display: flex;align-items: center;justify-content: space-between;width: 100%">
				<view class="text-sm">
					<view class="text-gray margin-bottom-xs">
						抢单截止时间：
					</view>
					<view class="color-red">
						{{orderData.dockingPeopleTime}}
					</view>
				</view>
				<button class="cu-btn bg-sub" style="color: white;background-color: #006BFE"
					@click="robOrder">立即抢单</button>
				<!--         <button class="cu-btn flex-sub bg-sub" @click="showToast">取消订单</button>-->
				<!--         取消异常，只有异常已创建且 status != 0 时显示 -->
			</view>

			<!-- 飞手按钮 -->
			<template v-if="theme=='fs'">
				<button class="cu-btn flex-sub bg-sub" v-if="orderException && orderException.status === '2'
				 && (orderData.createType === '2' || orderData.exceptionType === '1')"
					@click="onCancelException">取消异常
				</button>
				<button class="cu-btn  flex-sub bg-sub"
					v-if="(orderData.status > 1 && orderData.status < 5 && orderData.status != 2)
					 || orderData.status > 12 && orderData.status !== 17"
					@click="onReport">上报异常
				</button>
				<button class="cu-btn flex-sub bg-main" @click="reStart"
					v-if="orderData.status >= 12&&orderData.status!=16 &&
					(orderData.createType === '2' || orderData.exceptionType === '1')">
					继续任务
				</button>
					<!-- 飞手可以不接单 -->
				<button class="cu-btn flex-sub bg-sub" v-if="orderData.status == 2"
					@click="onCancelOrder">取消订单
				</button>
					<button class="cu-btn flex-sub bg-main" v-if="orderData.status == 2"
					@click="onConfirmOrder">订单确认
				</button>
				<button class="cu-btn flex-sub bg-main" v-if="orderData.status == 16" @click="onSigin">到达签到</button>
				<button class="cu-btn flex-sub bg-main" v-if="orderData.status > 2 && orderData.status < 5"
					@click="onUpdata">进度上传
				</button>
			</template>

			<!-- 农户按钮 -->
			<view v-else class="text-right w-100 flex">
				<!-- 没接单前农户能取消 -->
				<button class="cu-btn bg-red flex-sub" v-if="orderData.status == 1 || orderData.status == 17"
				 @click="onCancelOrder">取消订单
				</button>
				<button class="cu-btn bg-main margin-left-sm flex-sub" v-if="orderData.status == 1 || orderData.status == 17"
					@click="onEdit">修改订单
				</button>
				<button class="cu-btn bg-green margin-left-sm flex-sub" @click="onReport"
					v-if="(orderData.status > 2 && orderData.status < 6) || orderData.status >= 12 &&
					orderData.status !== 17">上报异常
				</button>
				<button v-if="orderData.status == 5" class="cu-btn bg-green margin-left-sm flex-sub"
					@click="handleAuth">去审核
				</button>
				<button v-if="orderData.commentContent == null &&
							(
							(orderData.status == 6 && orderData.isStatus == 2) ||
							(orderData.status == 7 && orderData.isStatus == 1) ||
							(orderData.status == 9 && orderData.isStatus == 1)
							)" class="cu-btn bg-green margin-left-sm flex-sub" @click="handleEval">
					去评价
				</button>

				<button class="cu-btn flex-sub bg-main"  v-if="orderData.status >= 12 && orderData.status != 16 &&
					(orderData.createType === '1' || orderData.exceptionType === '1')"
					@click="reStart">继续任务
				</button>
				<button class="cu-btn flex-sub bg-sub" v-if="orderException && orderException.status === '2' && 
					(orderData.createType === '1' || orderData.exceptionType === '1')"
					@click="onCancelException">取消异常
				</button>


			</view>
		</view>

		<uv-modal ref="cancelContinueModal" title="提示" cancelText="取消" confirmText="确定"
			@confirm="confirmCancelAndContinue">
			<view class="slot-content text-center">
				当前订单异常中，是否取消异常并继续任务？
			</view>
		</uv-modal>

		<AuthModal ref="authModal" @success="onRefresh" />
		<ConfirmOrderModal ref="confirmOrderModal" @success="onRefresh" />
		<CancelOrderModal ref="cancelOrderModal" @success="onRefresh" />
	</view>
</template>

<script>
	import OrderDetailCard from '@/components/orderDetailCard/index.vue'
	import MonitorInfo from '@/components/monitorInfo/index.vue'
	import WorkInfo from '@/components/workInfo/index.vue'
	import SettleInfo from '@/components/settleInfo/index.vue'
	import AuthModal from '@/components/authModal/index.vue'
	import EvaluateInfo from '@/components/evaluateInfo/index.vue'
	import ConfirmOrderModal from '@/components/confirmOrderModal/index.vue'
	import CancelOrderModal from '@/components/cancelOrderModal/index.vue'
	// import SignInTip from "@/components/signInTip/index.vue";
	import {
		mapGetters
	} from 'vuex'

	export default {
		components: {
			OrderDetailCard,
			MonitorInfo,
			WorkInfo,
			SettleInfo,
			AuthModal,
			EvaluateInfo,
			ConfirmOrderModal,
			CancelOrderModal
			// SignInTip
		},
		computed: {
			...mapGetters(['theme'])
		},
		data() {
			return {
				urls: [
					'https://cdn.uviewui.com/uview/album/1.jpg',
					'https://cdn.uviewui.com/uview/album/2.jpg',
					'https://cdn.uviewui.com/uview/album/3.jpg',
					'https://cdn.uviewui.com/uview/album/4.jpg',
					'https://cdn.uviewui.com/uview/album/7.jpg',
					'https://cdn.uviewui.com/uview/album/6.jpg',
					'https://cdn.uviewui.com/uview/album/5.jpg'
				],
				orderData: {},
				fisrtData: {},
				monitorData: [],
				picData: {
					drugImage: [],
					prescribeImage: [],
					homeworkImage: [],
					endImage: [],
					trajectoryImage: [],
				},
				orderException: {
					status: '0'
				},
				isRestarting: false,
				robFlag: true,
			}
		},
		onLoad(data) {
			this.id = data.id
			if (this.theme == 'farmer') {
				uni.setNavigationBarColor({
					backgroundColor: '#0BCA89',
					frontColor: '#ffffff'
				});
			} else {
				uni.setNavigationBarColor({
					backgroundColor: '#006BFE',
					frontColor: '#ffffff',
				});
			}
			// this.fetchDetail()
			// this.fetchOrderLogList()
		},
		onShow() {
			this.fetchDetail()
			this.fetchOrderLogList()
			this.fetchExceptionDetail()
			if(this.theme == 'fs') {
				this.canRobOrder()
			}
		},
		onPullDownRefresh() {
			this.fetchDetail()
			this.fetchOrderLogList()
			this.fetchExceptionDetail()
		},
		methods: {
			// 新增：获取异常详情
			fetchExceptionDetail() {
				this.$http.get(`/cadre/orderException/getDatailList/${this.id}`)
					.then(res => {
						this.orderException = res.data
					})
			},
			// 新增：取消异常
			// onCancelException() {
			//       this.$http.get(`/cadre/orderException/cancel/${this.id}`, {
			//         params: { isStatus: 1 }
			//       })
			//     .then(res => {
			//       uni.showToast({ title: '取消成功', icon: 'success' })
			// this.orderException.status = 3
			//       this.fetchExceptionDetail()
			// this.fetchOrderLogList()
			// this.fetchDetail()
			//     })
			// },
			onCancelException() {
				this.$http.get(`/cadre/orderException/cancel/${this.id}`, {
					params: {isStatus: 1,cancelAnomaly: 1}}).then(res => {
						if (res.code === 200) {
						uni.showToast({
							title: '取消成功',
							icon: 'success'
						});
						const data = res.data.data;
						if (data && Object.keys(data).length > 0) {
							this.orderException = data;
						} else {
							this.orderException.status = 3;
							console.log('1111111', this.orderException.status);
						}
						this.fetchExceptionDetail();
						this.fetchOrderLogList();
						this.fetchDetail();
						} else if (res.code === 500) {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
						} else {
						uni.showToast({
							title: res.msg || '操作失败',
							icon: 'none',
							duration: 2000
						});
						}
					});
				},
			handleCallPhone() {
				const phoneNumber = this.theme == 'farmer' ? this.orderData.mobile : this.orderData.regionPhone;
				uni.makePhoneCall({
					phoneNumber: phoneNumber, // 电话号码
					success: function() {
						console.log('拨打电话成功');
					},
					fail: function() {
						console.log('拨打电话失败');
					}
				});
			},
			// 签到
			onSigin() {
				// this.$refs.signInTip.show(this.orderData);
        if (this.orderData.frozenReason && this.orderData.frozenReason !== '') {
          uni.showToast({
            title: '当前订单已被冻结，暂不支持此操作',
            icon: 'none',
            duration: 2000
          });
          return;
        }
				uni.$uv.route({
					url: '/subPages/pages/signIn/index',
					params: {
						id: this.orderData.id,
						orderLogId: this.orderData.orderLogId,
						address: this.orderData.address,
						lng: this.orderData.lng,
						lat: this.orderData.lat,
						frozenReason: this.orderData.frozenReason
					}
				})
			},
			// 上报异常
			onReport() {
				if (this.orderData.frozenReason && this.orderData.frozenReason.toString().trim() !== '') {
					return uni.showToast({
					title: '当前订单已被冻结，暂不支持此操作',
					icon: 'none',
					duration: 2000,
					});
				}
				uni.$uv.route({
					url: '/subPages/pages/exceptionList/index',
					params: {
						id: this.orderData.id,
						orderLogId: this.orderData.orderLogId,
						homeworkStartTime: this.orderData.homeworkStartTime,
						dockingPeopleTime: this.orderData.dockingPeopleTime
					}
				})
			},
			// reStart() {
			// 	this.$http.get('/cadre/orderException/continueTask/' + this.orderData.id
			// 	).then(res => {
			// 		this.fetchDetail()
			// 		this.fetchOrderLogList()
			// 	})
			// },
			// 订单确认
			onConfirmOrder() {
				this.$refs.confirmOrderModal.show(this.orderData);
			},
			onCancelOrder() {
				this.$refs.cancelOrderModal.show({theme: this.theme, id: this.orderData.id});
			},
			reStart() {
				if (this.orderData.status === 12 || this.orderData.status === 15 || this.orderData.status === 14) {
					this.confirmCancelAndContinue(); // 直接执行继续任务的逻辑
				} else {
					this.$refs.cancelContinueModal.open();
				}
			},
			_doContinueTask() {
				const status = String(this.orderException?.status || '0')
				const exceptionStatus = status === '2' ? 2 : 0
				const url = `/cadre/orderException/continueTask/${this.orderData.id}/${exceptionStatus}`
				this.$http.get(url).then(() => {
					this.fetchDetail()
					this.fetchOrderLogList()
					this.fetchExceptionDetail()
				})
			},
			confirmCancelAndContinue() {
				this.$http.get(`/cadre/orderException/continueTask/${this.orderData.id}/${this.orderException.status==2?2:0}`).then((res) => {
					if (res.code === 200) {
						this.$refs.cancelContinueModal.closeLoading()
						this.$refs.cancelContinueModal.close();
						this.fetchDetail()
						this.fetchOrderLogList()
						this.fetchExceptionDetail()
					} else if (res.code === 500) {
						this.$refs.cancelContinueModal.closeLoading()
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					} else {
						this.$refs.cancelContinueModal.closeLoading()
						uni.showToast({
							title: res.msg || '操作失败',
							icon: 'none'
						});
					}
				})
			},

			onUpdata() {
        if (this.orderData.frozenReason && this.orderData.frozenReason !== '') {
          uni.showToast({
            title: '当前订单已被冻结，暂不支持此操作',
            icon: 'none',
            duration: 2000
          });
          return;
        }
				uni.$uv.route({
					url: '/subPages/pages/progressUpload/index',
					params: {
						id: this.orderData.id,
						orderLogId: this.orderData.orderLogId,
						frozenReason: this.orderData.frozenReason
					}
				})
			},
			onRefresh() {
				this.fetchDetail()
				this.fetchOrderLogList()
			},
			// 判断飞手是否可以抢单
			canRobOrder() {
				this.$http.get(`/cadre/orderException/details/${this.id}`).then(res => {
					// console.log(123, res)
					if(res.code == 200) {
						if(res.data.createType == 2) {
							this.robFlag = true
						} else {
							this.robFlag = false
						}
					}
				})
			},
			fetchDetail() {
				let _this = this;
				this.$http.get('/cadre/assignOrder/getDatail', {
					params: {
						id: this.id,
						...(this.$hd.position || {}),
					}
				}).then(res => {
					res.data.status = res.data.status * 1
					this.orderData = res.data
					//获取预估金额
					// this.$http.get('/cadre/highSeasOrder/sumAmount', {
					// 	params: {
					// 		cropType: _this.orderData.cropType,
					// 		area: _this.orderData.area,
					// 		drugRequire: _this.orderData.drugRequire
					// 	}
					// }).then(yRes => {
					// 	_this.orderData.money = yRes.data
					// 	if (yRes == "500") _this.orderData.money = null;
					// })

					if (res.data.drugImage) {
						this.picData.drugImage = res.data.drugImage.split(',').map(item => (
							`${this.$hd.baseUrl}/common/file/${item}`))
					}
					if (res.data.prescribeImage) {
						this.picData.prescribeImage = res.data.prescribeImage.split(',').map(item => (
							`${this.$hd.baseUrl}/common/file/${item}`))
					}
					if (res.data.homeworkImage) {
						this.picData.homeworkImage = res.data.homeworkImage.split(',').map(item => (
							`${this.$hd.baseUrl}/common/file/${item}`))
					}
					if (res.data.endImage) {
						this.picData.endImage = res.data.endImage.split(',').map(item => (
							`${this.$hd.baseUrl}/common/file/${item}`))
					}
					if (res.data.trajectoryImage) {
						this.picData.trajectoryImage = res.data.trajectoryImage.split(',').map(item => (
							`${this.$hd.baseUrl}/common/file/${item}`))
					}
				})
			},
			// 监控信息
			fetchOrderLogList() {
				let url = this.theme == 'fs' ? '/cadre/assignOrder/getOrderLogListByFly' :
					'cadre/highSeasOrder/getOrderLogListByFly'
				this.$http.get(url, {
					params: {
						id: this.id
					}
				}).then(res => {
					const rows = res.data.rows
					this.fisrtData = res.data.rows[0]
					const subList = res.data.rows.slice(1)
					let findex = subList.findIndex(item => !item.createTime)
					// console.log('subList.length', findex, subList.length)
					if (subList[subList.length - 1].status == 9 || findex == -1) {
						this.monitorData = subList.map((item, index) => {
							item.step = 'pre'
							return item
						})
					} else if (findex == subList.length - 1) {
						this.monitorData = subList.map((item, index) => {
							item.step = 'pre'
							return item
						})
					} else {
						this.monitorData = subList.map((item, index) => {
							if (index == findex - 1) {
								item.step = 'cur'
							} else if (index < findex - 1) {
								item.step = 'pre'
							} else {
								item.step = 'next'
							}
							return item
						})
					}
				})
			},
			showOrdrTip() {
				this.$refs.orderTip.open();
			},
			confirmAdd() {},
			confirm() {},
			//立即抢单
			robOrder() {
				let _this = this;
				uni.showModal({
					title: '抢单提示',
					content: '您确定要抢接该订单吗？',
					success: function(res) {
						if (res.confirm) {
							let user = uni.getStorageSync('userInfo');
							//判断用户是否实名
							if (user.authStatus == "1") {
								//已实名

								//抢单操作
								uni.showLoading({
									title: '加载中'
								});
								let formData = {
									"flyerId": user.id,
									"orderId": _this.orderData.id,
									"orderCode": _this.orderData.orderCode
								}
								_this.$http
									.post("/cadre/assignOrder/grabOrder", {}, {
										data: JSON.stringify(formData)
									})
									.then((res) => {
										uni.hideLoading();
										if (res.code == "200") {
											uni.showModal({
												title: res.msg,
												showCancel: false,
												confirmText: '知道了'
											});
											_this.onRefresh()
										} else if (res.code == "500") {
											uni.showToast({
												title: res.msg,
												icon: 'none',
												duration: 2000
											});
										} else {
											uni.showToast({
												title: res.msg || "抢单失败",
												icon: 'none',
												duration: 2000
											});
										}
									})
							} else {
								//未实名
								uni.showModal({
									title: '抢单提示',
									content: '您还未完成飞手认证，请先前往完成认证再进行抢单！',
									success: function(res) {
										if (res.confirm) {
											uni.navigateTo({
												url: '/subPages/pages/authInfo/index'
											});
										}
									}
								})
							}
						}
					}
				});
			},
			showToast() {
				uni.showToast({
					title: '系统错误',
					// title: '抢单失败',
					duration: 2000,
					// icon: 'error'
					// image: '../../static/icon-success.png'
					image: `${this.$hd.baseUrl}/images/icon-mistake.png`
					// image: '../../static/icon-fail.png'
				});
				return
				// this.$refs.toast.show({
				// 	type: 'default',
				// 	icon: 'close',
				// 	title: '正在加载',
				// 	message: "正在加载",
				// 	complete() {
				// 		console.log(1)
				// 	}
				// })
			},
			onCancel() {
				uni.$uv.route({
					url: '/subPages/pages/cancelOrder/index',
					params: {
						id: this.orderData.id,
					}
				})
			},
			// 修改
			onEdit() {
				uni.$uv.route({
					url: '/subPages/pages/bookOrder/index',
					params: {
						id: this.orderData.id,
						homeworkType: this.orderData.homeworkType,
						orderLogId: this.orderData.orderLogId,
						isEdit: true
					}
				})
			},
			handlePay() {},
			// 完工审核
			handleAuth() {
				if (this.orderData.frozenReason && this.orderData.frozenReason.toString().trim() !== '') {
					return uni.showToast({
					title: '当前订单已被冻结，暂不支持此操作',
					icon: 'none',
					duration: 2000,
					});
				}
				this.$refs.authModal.show(this.orderData);
			},
			handleEval() {
				uni.$uv.route({
					url: '/subPages/pages/evaluation/index',
					params: {
						flyerName: this.orderData.flyerName,
						id: this.orderData.id
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.foot-box {
		position: fixed;
		bottom: 0%;
		left: 0;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx;
		background-color: #fff;

		.cu-btn {
			border-radius: 10rpx;
			// color: #fff;
			margin-left: 20rpx;
			margin-right: 20rpx;
		}

		.bg-sub {
			background-color: #E9ECFF;
			color: #006BFE;
		}

		.bg-main {
			background: #006BFE;
			color: #fff
		}
	}
</style>